﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using CommunityServer.WebServices.MediaGalleries;
using System.Threading;

namespace nb.development.csmediamanager
{
    public partial class FileAttachment : Form
    {
        public FileAttachment(MediaGallery gallery, Guid siteid)
        {
            InitializeComponent();
            this.gallery = gallery;
            this.siteid = siteid;
            if (!gallery.Settings.EnableExternalLinks.Value)
                groupBox2.Enabled = false;
            this.Height = height;
            this.update = false;
            this.post = null;
        }

        public FileAttachment(MediaGallery gallery, Guid siteid, MediaGalleryPost post)
        {
            InitializeComponent();
            this.gallery = gallery;
            this.siteid = siteid;
            if (!gallery.Settings.EnableExternalLinks.Value)
                groupBox2.Enabled = false;
            this.Height = height;
            this.update = true;
            this.post = post;
        }

        private MediaGalleryPost post;
        private bool update;

        private Guid siteid;
        private MediaGallery gallery;

        private int fullheight = 235;
        private int height = 188;

        private string filename;

        public string Filename
        {
            get { return filename; }
        }

        private Guid temporaryPostAttachment;
        /// <summary>
        /// The GUID returned from the Uploading/Attaching of the File
        /// </summary>
        public Guid TemporaryPostAttachment
        {
            get { return temporaryPostAttachment; }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                FileInfo file = new FileInfo(openFileDialog1.FileName);
                if (file.Extension.ToLower().Equals(".jpg") || file.Extension.ToLower().Equals(".jpeg") || file.Extension.ToLower().Equals(".gif") || file.Extension.ToLower().Equals(".png") || file.Extension.ToLower().Equals(".bmp"))
                    this.Height = fullheight;
                else this.Height = height;
                txtFile.Text = file.FullName;
                editorFilename = string.Empty;
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            panel1.Enabled = false;
            btnOK.Enabled = false;
            btnCancel.Enabled = false;
            this.ControlBox = false;
            uploading.Show();
            uploadProgs.Value = 0;
            uploadProgs.Maximum = 1;
            if (update)
            {
                AttachmentUpdater au;
                if (radLocal.Checked)
                    if (!string.IsNullOrEmpty(editorFilename)) au = new AttachmentUpdater(this.siteid, this.post.Id, new FileInfo(editorFilename).OpenRead(), editorFilename);
                    else au = new AttachmentUpdater(this.siteid, this.post.Id, new FileInfo(txtFile.Text).OpenRead(), new FileInfo(txtFile.Text).Name);
                else au = new AttachmentUpdater(this.siteid, this.post.Id, this.txtUrl.Text);
                au.UpdateCompleted += new UpdatedAttachment(au_UpdateCompleted);
                Cursor = Cursors.WaitCursor;
                Thread t = new Thread(new ThreadStart(au.UpdateAttachment));
                t.Start();
            }
            else
            {
                AttachmentUploader au;
                if (radLocal.Checked)
                    if (!string.IsNullOrEmpty(editorFilename)) au = new AttachmentUploader(gallery.Id, this.siteid, new FileInfo(editorFilename).OpenRead(), editorFilename);
                    else au = new AttachmentUploader(gallery.Id, this.siteid, new FileInfo(txtFile.Text).OpenRead(), new FileInfo(txtFile.Text).Name);
                else au = new AttachmentUploader(gallery.Id, this.siteid, this.txtUrl.Text);
                Cursor = Cursors.WaitCursor;
                au.UploadCompleted += new UploadedAttachment(au_UploadCompleted);
                Thread t = new Thread(new ThreadStart(au.UploadAttachment));
                t.Start();
            }
        }

        void au_UpdateCompleted()
        {
            if (uploadProgs.InvokeRequired)
            {
                UpdatedAttachment done = new UpdatedAttachment(au_UpdateCompleted);
                try { uploadProgs.Invoke(done); }
                catch { }
            }
            else
            {
                uploadProgs.Value = 1;
                if (radLocal.Checked)
                {
                    if (!string.IsNullOrEmpty(editorFilename)) new FileInfo(editorFilename).Delete();
                    this.filename = txtFile.Text.Remove(0, txtFile.Text.LastIndexOf('\\') + 1).Trim();
                }
                else this.filename = txtUrl.Text.Remove(0, txtUrl.Text.LastIndexOf('/') + 1).Trim();
                DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        void au_UploadCompleted(Guid guid)
        {
            if (uploadProgs.InvokeRequired)
            {
                UploadedAttachment done = new UploadedAttachment(au_UploadCompleted);
                try { uploadProgs.Invoke(done, guid); }
                catch { }
            }
            else
            {
                uploadProgs.Value = 1;
                if (radLocal.Checked)
                    this.filename = txtFile.Text.Remove(0, txtFile.Text.LastIndexOf('\\') + 1).Trim();
                else this.filename = txtUrl.Text.Remove(0, txtUrl.Text.LastIndexOf('/') + 1).Trim();
                this.temporaryPostAttachment = guid;
                DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void radRemote_Click(object sender, EventArgs e)
        {
            radRemote.Checked = true;
            radLocal.Checked = false;
            groupBox1.Enabled = false;
            groupBox2.Enabled = true;
        }

        private void radLocal_Click(object sender, EventArgs e)
        {
            radLocal.Checked = true;
            radRemote.Checked = false;
            groupBox1.Enabled = true;
            groupBox2.Enabled = false;
        }

        private void txtUrl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (txtUrl.Text.Length > 0) btnOK.Enabled = true;
            else btnOK.Enabled = false;
        }

        private void txtFile_TextChanged(object sender, EventArgs e)
        {
            if (txtFile.Text.Length > 0) btnOK.Enabled = true;
            else btnOK.Enabled = false;
        }

        private string editorFilename = string.Empty;

        private void btnEditImage_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                FileInfo file = new FileInfo(txtFile.Text);
                Bitmap bm = new Bitmap(file.OpenRead());
                ImageEditor ie = new ImageEditor(bm, file.Name);
                if (ie.ShowDialog(this) == DialogResult.OK) editorFilename = ie.Filename;
            }
        }

        private void FileAttachment_FormClosing(object sender, FormClosingEventArgs e)
        {
            try { if (!string.IsNullOrEmpty(editorFilename)) new FileInfo(editorFilename).Delete(); }
            catch { }
        }
    }
}
